// @ts-nocheck
import { useSearchParams, useRoutes } from 'react-router-dom'
import getRouter from './router'
import './App.less'
import http from './utils/Axios/index'
import React, { useEffect, useState } from 'react'
import { Toast, Button, Modal } from 'antd-mobile'
import {
    getAccessToken,
    getCurrentUser,
    getToken,
    setAccessToken,
    setToken,
    setRefreshToken,
} from './utils/authority'
import ReactDOM from 'react-dom'
import TroyRtc from 'troyrtc-sdk'

const IncomingCallModal = ({
    callerName,
    onOk,
    onCancel,
    onTimeout,
    hasRecived,
}) => {
    const [countdown, setCountdown] = useState(10)
    const [timer, setTimer] = useState<any>(null)
    const [modalVisible, setModalVisible] = useState(true)

    const handleTimeout = () => {
        clearInterval(timer)
        setModalVisible(false)
        onTimeout()
    }

    useEffect(() => {
        let interval: any = null

        if (countdown > 0) {
            interval = setInterval(() => {
                setCountdown(prevCountdown => prevCountdown - 1)
            }, 1000)
        } else {
            handleTimeout()
        }

        return () => {
            if (interval) {
                clearInterval(interval)
            }
        }
    }, [countdown])


    const handleOk = () => {
        clearInterval(timer)
        setModalVisible(false)
        hasRecived()
        onOk()
    }

    const handleCancel = () => {
        clearInterval(timer)
        setModalVisible(false)
        onCancel()
    }



    const actions: any = [
        { text: '接听', onClick: handleOk, primary: true },
        { text: '挂断', onClick: handleCancel },
    ]

    return ReactDOM.createPortal(
        <div>
            <Modal
                visible={modalVisible}
                // transparent
                // maskClosable={false}
                onClose={handleCancel}
                afterClose={() => {
                    setModalVisible(false)
                }}
                title={`收到${callerName}的来电，请在${countdown}s内接听`}
                actions={actions}
            />
        </div>,
        document.getElementById('root'),
    )
}

const Rtc: React.FC<any> = () => {
    const [troyRtc, setTroyRtc] = useState(null)
    const [status, setStatus] = useState({
        type: 'init',
        data: '',
        tag: '',
    })
    const [userInfo, setUserInfo] = useState({})
    const [showModal, setShowModal] = useState(false)
    const [incomingData, setIncomingData] = useState({
        data: {
            callUserId: '',
            uuid: '',
            chatroomId: '',
            chatroomName: '',
            calleeUserId: '',
            callUsername: '',
        },
        uuid: '',
    })
    const [isVideo, setIsVideo] = useState(true)
    const [isAudio, setIsAudio] = useState(true)
    const getUserInfoFormStorage = () => {
        const data = JSON.parse(localStorage.getItem('user_info')) || ''

        if (data && data.data) {
            setUserInfo(data.data)
            handleLoginToSignalServer(data.data)
        }
    }
    const handleLoginToSignalServer = userInfo => {
        const options = {
            code: 'VHJveVJUQzpUcm95UlRDLXNlY3JldA==',
            userId: String(userInfo?.id || userInfo?.user_id),
            constraints: {
                audio: true,
                video: true,
            },
            url: 'wss://119.4.188.151:9222',
            // url: window.sdkUrl,
            // container: document.getElementById('test'),
            userName: userInfo?.name,
            nickName: userInfo?.name,
        }
        const troyRtcIns = new TroyRtc(options)

        troyRtcIns.onStatusChange = e => {
            setStatus(e)
        }
        setTroyRtc(troyRtcIns.init())
    }
    useEffect(() => {
        getUserInfoFormStorage()
    }, [window.LoginUserInfo])

    const handleOk = () => {
        setShowModal(false)
        troyRtc.meeting.callAnswer({
            container: document.getElementById('test'),
            uuid: incomingData.uuid,
            data: {
                callUserId: incomingData.data.callUserId,
                callUsername: incomingData.data.callUsername,
                chatroomId: incomingData.data.chatroomId,
                chatroomName: incomingData.data.chatroomName,
                userId: incomingData.data.calleeUserId,
                username: userInfo?.name,
                calleeStatus: 200,
            },
        })
    }
    const handleCancel = () => {
        setShowModal(false)
        troyRtc.meeting.callAnswer({
            container: document.getElementById('test'),
            uuid: incomingData.uuid,
            data: {
                callUserId: incomingData.data.callUserId,
                callUsername: incomingData.data.callUsername,
                chatroomId: incomingData.data.chatroomId,
                chatroomName: incomingData.data.chatroomName,
                userId: incomingData.data.calleeUserId,
                username: userInfo?.name,
                calleeStatus: 480,
            },
        })
    }
    const handleTimeout = () => {
        setShowModal(false)
        troyRtc.meeting.callAnswer({
            container: document.getElementById('test'),
            uuid: incomingData.uuid,
            data: {
                callUserId: incomingData.data.callUserId,
                callUsername: incomingData.data.callUsername,
                chatroomId: incomingData.data.chatroomId,
                chatroomName: incomingData.data.chatroomName,
                userId: incomingData.data.calleeUserId,
                username: userInfo?.name,
                calleeStatus: 401,
            },
        })
    }
    const hasRecived = () => {
        const dom = document.getElementById('rtc')
        dom.style.zIndex = '1'
    }
    const hangup = () => {
        troyRtc.meeting.hangup()
        const dom = document.getElementById('rtc')
        dom.style.zIndex = '-1'
        setShowModal(false)
    }
    useEffect(() => {
        const { type, data, tag } = status
        if (type == 'connected') {
            Toast.show({
                content: '已连接至即时通讯服务器',
            })
        }
        if (type == 'receivedCall') {
            setShowModal(true)
            setIncomingData(data)

            uni.postMessage({
                data: {
                    action: 'recCall',
                },
            })
        }
        if (type == 'chatRoomUsers') {
            if (data.data) {
                let res = data.data.users

                res.forEach(item => {
                    if (
                        item.userId == userInfo?.id ||
                        item.userId == userInfo?.user_id
                    ) {
                        setIsAudio(item.audioType == 2 ? true : false)
                        setIsVideo(item.videoType == 2 ? true : false)
                    }
                })
            }
        }
    }, [status])
    const handleVideoChange = e => {
        const res = troyRtc.meeting.switchVideoOrAudio('video', e)
        if (res) {
            setIsAudio(e)
        }
    }
    const handleAudioChange = e => {
        const res = troyRtc.meeting.switchVideoOrAudio('audio', e)
        if (res) {
            setIsAudio(e)
        }
    }
    return (
        <div id="rtc">
            <div id="test"></div>
            <div className="troyRtcControl">
                {isAudio ? (
                    <div
                        className="troyRtc_Quite_on"
                        onClick={() => {
                            handleAudioChange(false)
                        }}
                    ></div>
                ) : (
                    <div
                        className="troyRtc_Quite_off"
                        onClick={() => {
                            handleAudioChange(true)
                        }}
                    ></div>
                )}

                <div className="troyRtc_Hangup" onClick={hangup}></div>
                {isVideo ? (
                    <div
                        className="troyRtc_switch_on"
                        onClick={() => {
                            handleVideoChange(false)
                        }}
                    ></div>
                ) : (
                    <div
                        className="troyRtc_switch_off"
                        onClick={() => {
                            handleVideoChange(true)
                        }}
                    ></div>
                )}
            </div>
            {showModal && (
                <IncomingCallModal
                    callerName={incomingData?.data?.callUsername || ''}
                    onOk={handleOk}
                    onCancel={handleCancel}
                    onTimeout={handleTimeout}
                    hasRecived={hasRecived}
                />
            )}
        </div>
    )
}
function App() {
    const [searchParams, setSearchParams] = useSearchParams()
    const code = searchParams.get('code')
    const isFromRzt = sessionStorage.getItem('isFromRzt')
    const communicateCodet = searchParams.get('communicateCode')
    if (communicateCodet) sessionStorage.setItem('communicateCode', true)
    const communicateCode = sessionStorage.getItem('communicateCode')
    if (searchParams.get('token')) {
        searchParams.get('token')
        const token = searchParams.get('token')
        const title = searchParams.get('title')
        setAccessToken(token)
        setToken(`bearer ${token}`)
        setRefreshToken(token)
        localStorage.setItem('users', searchParams.get('user'))
        localStorage.setItem(
            'chooseOne',
            title == '待签事件'
                ? '1'
                : title == '待办事件'
                    ? '2'
                    : title == '交办事件'
                        ? '4'
                        : '3',
        )
        localStorage.setItem('curret', '0000e')
    }

    let hasLogin = getToken() && getAccessToken() && getCurrentUser()

    const router = getRouter(hasLogin)
    function getCurrentFormattedTime() {
        // 创建一个表示当前时间的 Date 对象
        var currentDate = new Date()

        // 获取当前时间的年份
        var year = currentDate.getFullYear()

        // 获取当前时间的月份（注意：返回的月份是从 0 开始计数的）
        var month = currentDate.getMonth() + 1

        // 获取当前时间的日期
        var day = currentDate.getDate()

        // 获取当前时间的小时
        var hours = currentDate.getHours()

        // 获取当前时间的分钟
        var minutes = currentDate.getMinutes()

        // 获取当前时间的秒数
        var seconds = currentDate.getSeconds()

        // 格式化月份、日期、小时、分钟和秒数，确保它们始终是两位数
        month = (month < 10 ? '0' : '') + month
        day = (day < 10 ? '0' : '') + day
        hours = (hours < 10 ? '0' : '') + hours
        minutes = (minutes < 10 ? '0' : '') + minutes
        seconds = (seconds < 10 ? '0' : '') + seconds

        // 构建格式化后的时间字符串
        var formattedTime =
            year +
            '-' +
            month +
            '-' +
            day +
            ' ' +
            hours +
            ':' +
            minutes +
            ':' +
            seconds

        return formattedTime
    }

    useEffect(() => {
        if (hasLogin) {
            const data = JSON.parse(localStorage.getItem('user_info')) || ''

            window.msgFromUniapp = function (arg) {
                if (arg?.location && data) {
                    const { lng, lat } = arg.location
                    console.log(
                        `开始调用上报接口时间${getCurrentFormattedTime()}`,
                        JSON.stringify(data),
                    )
                    http('post', '/app/keeper-grid/attendanceDailyTrack/save', {
                        trackLong: lng,
                        trackLat: lat,
                    })
                        .then(data => {
                            console.log(
                                `收到上报返回时间${getCurrentFormattedTime()}`,
                                JSON.stringify(data),
                            )
                        })
                        .catch(res => {
                            console.log(
                                `收到错误信息时间${getCurrentFormattedTime()}`,
                                JSON.stringify(res),
                            )
                        })
                    http('get', '/app/keeper-grid/teamUserInfo/heartbeat')
                        .then(data => {
                            console.log(data)
                        })
                        .catch(res => {
                            console.log(res)
                        })


                    console.log('APPTSX', JSON.stringify(arg))
                }
            }
        }
    }, [hasLogin])

    return (
        <div className="main">
            {/* {!communicateCode && !code && !isFromRzt && <Rtc></Rtc>} */}

            {useRoutes(router)}
        </div>
    )
}
export default App
